﻿#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <exception>
// 共享资源
int shared_counter = 0;
std::mutex mtx;
// 模拟工作函数：对共享计数器加 1 多次
void worker(int thread_id, int increments) {
    try {
        for (int i = 0; i < increments; ++i) {
            // 作用域内自动加锁，离开作用域自动解锁
            std::lock_guard<std::mutex> lock(mtx);
            // 临界区开始
            ++shared_counter;
            // 可以安全地打印
            std::cout << "Thread " << thread_id << " incremented counter to " << shared_counter << std::endl;
            // 临界区结束
            // lock_guard 离开作用域自动解锁
        }
        // 模拟某种条件下异常抛出
        if (thread_id == 2) {
            throw std::runtime_error("Thread 2 encountered an error!");
        }
    }
    catch (const std::exception& e) {
        // 异常捕获，展示即使异常，锁也不会死锁
        std::cerr << "Exception in thread " << thread_id << ": " << e.what() << std::endl;
    }
}

int main() {
    const int num_threads = 3;
    const int increments_per_thread = 5;
    std::vector<std::thread> threads;
    // 启动多个线程
    for (int i = 1; i <= num_threads; ++i) {
        threads.emplace_back(worker, i, increments_per_thread);
    }
    // 等待所有线程结束
    for (auto& t : threads) {
        t.join();
    }
    std::cout << "Final shared counter value: " << shared_counter << std::endl;
    return 0;
}
